#include <iostream>
#include <string>

#include <boost/bind.hpp>
#include "boost/asio.hpp"

#include "BoostClient.h"

using namespace boost::asio;

void asyncClient()
{
    io_service service;
    ip::tcp::endpoint ep(ip::address::from_string(IP), POINT);
    socket_ptr sockClient(new ip::tcp::socket(service));
    sockClient->async_connect(ep, boost::bind(connect_handler, sockClient, _1)); //
    service.run();
}

void connect_handler(socket_ptr sock, const boost::system::error_code &ec)
{
    if (ec)
    {
        printf("error code = {%d}\n", ec);
    }
    else
    {
        printf("连接成功\n");
    }
    send_data(*sock.get());
    read_data(*sock.get());
}

/**
 * @brief 同步
 * 
 */
void syncClient()
{
    // 所有asio类都需要io_service对象
    io_service iosev;
    // socket对象
    ip::tcp::socket sock(iosev);
    // 连接端点，这里使用了本机连接，可以修改IP地址测试远程连接
    ip::tcp::endpoint ep(ip::address_v4::from_string(IP), POINT);
    // 连接服务器
    boost::system::error_code ec;
    sock.connect(ep, ec);
    // 如果出错，打印出错信息
    if (ec)
    {
        std::cout << boost::system::system_error(ec).what() << std::endl;
    }
    send_data(sock);
    read_data(sock);
}

int read_data(ip::tcp::socket &sock)
{
    boost::system::error_code ec;
    char buf[BLOCK_SIZE];
    // 接收数据
    memset(buf, 0, BLOCK_SIZE);
    int len = sock.read_some(buffer(buf), ec);
    std::cout.write(buf, len);
    std::cout << len << std::endl;
}

int send_data(ip::tcp::socket &sock)
{
    boost::system::error_code ec;
    // 发送数据
    // char buf[BLOCK_SIZE];
    // fill_buffer(buf);
    std::string value = "Hello world from client ";

    size_t len = sock.write_some(buffer(value), ec);
    std::cout << "writed " << len << " : " + value << std::endl;

    return len;
}

void fill_buffer(char *s)
{
    for (int i = 0; i < BLOCK_SIZE; i++)
    {
        s[i] = 'a';
    }
}

int main(int argc, char *argv[])
{
    {
        printf("start async conection");
        asyncClient();
    }
    {
        printf("start sync conection");
        // syncClient();
    }
    return 0;
}

//g++ BoostClient.cpp -lpthread -lboost_system -I/usr/local/include/boost -L/usr/local/lib -o client